import axios from 'axios'
import Cookies from 'js-cookie'
import {
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import {
  blobValidate,
  getAppId
} from '@/utils/index'
import {
  saveAs
} from 'file-saver'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})
var language = localStorage.getItem('language')

// 是否显示重新登录
export const isRelogin = {
  show: false
}
const errorCode = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误，请反馈给管理员'
}

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // config.headers['content-type'] = 'application/x-www-form-urlencoded;charset=utf-8'
    config.headers['Content-Type'] = 'application/json;'
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    if (language) {
      config.headers['Accept-Language'] = language
    }
    config.headers['appId'] = getAppId()
    if (config.meta && config.meta.loading) {
      store.commit('page/SET_PENDING', true)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 二进制数据则直接返回
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
      return response
    }
    let globalWarn = true
    if (response.config.meta && Object.hasOwnProperty.call(response.config.meta, 'globalWarn')) {
      globalWarn = response.config.meta.globalWarn
    }
    if (response.config.meta && response.config.meta.loading) {
      store.commit('page/SET_PENDING', false)
    }
    if (res.success !== 1) {
      if (globalWarn) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log(error)
    const code = error.response.status
    store.commit('page/SET_PENDING', false)
    console.log('err' + error) // for debug
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true
        MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          showClose: false,
          type: 'warning',
          closeOnPressEscape: false,
          closeOnClickModal: false
        }).then(() => {
          isRelogin.show = false
          store.dispatch('user/logout').then(() => {
            location.href = '/'
          })
        }).catch(() => {
          isRelogin.show = false
        })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)
let downloadLoadingInstance

// 通用下载方法
export function download(url, params, filename = '') {
  downloadLoadingInstance = Loading.service({
    text: '正在下载数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return service.post(url, params, {
    headers: {
      'Content-Type': 'application/json'
    },
    meta: {
      globalWarn: false
    },
    responseType: 'blob'
  }).then(async (response) => {
    const data = response.data
    const isLogin = await blobValidate(data)
    if (isLogin) {
      const blob = new Blob([data])
      if (!filename) {
        // 未设置文件名从header中获取
        try {
          filename = window.decodeURIComponent(response.headers['content-disposition'].split('=')[1], 'UTF-8').replace(/utf-8''/, '')
        } catch (e) {
          console.error(e)
          filename = +new Date() + '.xlsx'
        }
      }
      saveAs(blob, filename)
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = errorCode[rspObj.code] || rspObj.message || errorCode['default']
      Message.error(errMsg)
    }
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  })
}

// 通用下载方法
export function getDownload(url, filename = '') {
  downloadLoadingInstance = Loading.service({
    text: '正在下载数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return service.get(url, {
    headers: {
      'Content-Type': 'application/json'
    },
    meta: {
      globalWarn: false
    },
    responseType: 'blob'
  }).then(async (response) => {
    const data = response.data
    const isLogin = await blobValidate(data)
    if (isLogin) {
      const blob = new Blob([data])
      if (!filename) {
        // 未设置文件名从header中获取
        try {
          filename = window.decodeURIComponent(response.headers['content-disposition'].split('=')[1], 'UTF-8').replace(/utf-8''/, '')
        } catch (e) {
          console.error(e)
          filename = +new Date() + '.xlsx'
        }
      }
      saveAs(blob, filename)
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = errorCode[rspObj.code] || rspObj.message || errorCode['default']
      Message.error(errMsg)
    }
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  })
}

export default service
